<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Db;

class  Iphone extends Base {
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $useridddd = input('user_id');
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($useridddd,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    function validate_apple_pay($receipt_data){
        /**
         * 21000 App Store不能读取你提供的JSON对象
         * 21002 receipt-data域的数据有问题
         * 21003 receipt无法通过验证
         * 21004 提供的shared secret不匹配你账号中的shared secret
         * 21005 receipt服务器当前不可用
         * 21006 receipt合法，但是订阅已过期。服务器接收到这个状态码时，receipt数据仍然会解码并一起发送
         * 21007 receipt是Sandbox receipt，但却发送至生产系统的验证服务
         * 21008 receipt是生产receipt，但却发送至Sandbox环境的验证服务
         */
        function acurl($receipt_data, $sandbox=0){
            //小票信息
            $POSTFIELDS = array("receipt-data" => $receipt_data);
            $POSTFIELDS = json_encode($POSTFIELDS);

            //正式购买地址 沙盒购买地址
//            $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
            $url_buy     = "https://buy.itunes.apple.com/verifyReceipt";
            $url_sandbox = "https://sandbox.itunes.apple.com/verifyReceipt";
            $url = $sandbox ? $url_sandbox : $url_buy;
            //$url = $url_sandbox;

            //简单的curl
            $ch = curl_init($url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $POSTFIELDS);
            $result = curl_exec($ch);
            curl_close($ch);
            return $result;
        }
        // 验证参数
        if (strlen($receipt_data)<20){
            $result=array(
                'status'=>false,
                'message'=>'非法参数'
            );
            return $result;
        }
        // 请求验证
        $html = acurl($receipt_data);
        $data = json_decode($html,true);

        // 如果是沙盒数据 则验证沙盒模式
        if($data['status']=='21007'){
            // 请求验证
            $html = acurl($receipt_data, 1);
            $data = json_decode($html,true);
            $data['sandbox'] = '1';
        }

        if (isset($_GET['debug'])) {
            exit(json_encode($data));
        }

        // 判断是否购买成功
        if(intval($data['status'])===0){
            $result=array(
                'status'=>true,
                'message'=>'购买成功'
            );
        }else{
            $result=array(
                'status'=>false,
                'message'=>'购买失败 status:'.$data['status']
            );
        }
        return $result;
    }

    public function apppay()
    {
        $param = $_POST['param'];
        $res = $this->validate_apple_pay($param);
        if($res['status']){
            // 验证通过 此处可以是修改数据库订单状态等操作
            $num = $_POST['order_number'];
            Db::startTrans();
            try{
                // 修改订单状态
                Db::table('up_recharge')->where('recharge_num', $num)->setField('recharge_status', 2);

                // 跟新用户平台币
                $order_info = Db::table('up_recharge')
                    ->where('recharge_num', $num)
                    ->field('recharge_money_pingtai, recharge_user_id')
                    ->find();
                Db::table('up_u_user')->where('user_id', $order_info['recharge_user_id'])->setInc('user_balance', $order_info['recharge_money_pingtai']);

                // order表
                $order_insert = [
                    'order_type' => 1,
                    'order_price' => $order_info['recharge_money_pingtai'],
                    'order_time' => date('Y-m-d H:i:s'),
                    'order_user_id' => $order_info['recharge_user_id']
                ];
                Db::table('up_order')->insert($order_insert);
                Db::commit();
                return json_encode(['status'=>200,'msg'=>'购买成功']);
            }catch (\Exception $e) {
                Db::rollback();
                return json_encode(['status'=>0,'msg'=>'购买失败']);
            }
        }else{
            // 验证不通过
            return json_encode(['status'=>0,'msg'=>'购买失败']);
        }
    }

    /**
     * 确认订单页——支付
     * 哪一类型：which（1是会员购买 2是置顶包 3是刷新包）（bag对应表的id）
     * 如果是会员：authtype（买的是何种会员(2季度  3半年  4一年）
     * 哪方支付：type（1是支付宝  2是微信）
     */
    public function getPayInfo()
    {
        $params = input('param.');
        $order_number = date('YmdHis') . str_pad(mt_rand(1, 9999), 4, '0', STR_PAD_LEFT);//订单编号
        // 充值记录表
        $recharge_insert = [
            'recharge_user_id' => $params['user_id'],
            'recharge_money' => $params['order_price'], // 充值金额
            'recharge_type' => 3,
            'recharge_status' => 1,
            'recharge_time' => date('Y-m-d H:i:s'),
            'recharge_num' => $order_number,
            'recharge_money_pingtai' => $params['order_price'] // 充值平台币数量
        ];
        $result = Db::table('up_recharge')->insert($recharge_insert);
        $iphone_id = Db::table('up_ios_pay')
            ->where('money',$params['order_price'])
            ->value('ios_id');
        if($result){
            return json_encode(['status'=>200,'msg'=>$iphone_id,'order_number'=>$order_number]);
        }else{
            return json_encode(['status'=>0,'msg'=>'订单生成失败']);
        }
    }

}